﻿using Common.MyCustomException;
using Common.Result;
using Interface;
using IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model.Dto.Employee;
using Model.Entitys;

namespace TakeawayWebApi.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class CategoryController : ControllerBase
    {
        private readonly ICategoryService _categoryService;
        private readonly ILogger<EmployeeController> _logger;
        public CategoryController(ICategoryService categoryService, ILogger<EmployeeController> logger)
        {
            _categoryService = categoryService;
            _logger = logger;
        }

        [HttpGet("page")]
        public async Task<ApiResult> GetCategoryPage(int page, int pageSize, string? name)
        {
            var res = await _categoryService.GetCategoryPageAsync(page, pageSize, name);
            return ResultHelper.Success(res);
        }

        
        [HttpDelete("{id}")]
        public async Task<ApiResult> DeleteCategoryById(long id)
        {
            var res = await _categoryService.DeleteCategoryByIdAsync(id);
            if (res) return ResultHelper.Success("删除成功");
            return ResultHelper.Error("删除失败");
        }

        [HttpPut]
        public async Task<ApiResult> EditCategory(Category category)
        {
            long userId = Convert.ToInt64(HttpContext.User.Claims.ToList()[0].Value);
            var res = await _categoryService.EditCategoryAsync(category, userId);
            if (res) return ResultHelper.Success("修改成功");
            return ResultHelper.Error("修改失败");
        }
        
        [HttpGet("{id}")]
        public async Task<ApiResult> GetCategoryById(long id)
        {
            return ResultHelper.Success(await _categoryService.GetCategoryByIdAsync(id));
        }
        
        /// <summary>
        /// 根据type查找
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<ApiResult> GetCategorysByType(int type)
        {
            return ResultHelper.Success(await _categoryService.GetCategorysByTypeAsync(type));
        }

        [HttpPost]
        public async Task<ApiResult> SaveCategory(Category category)
        {
            long userId = Convert.ToInt64(HttpContext.User.Claims.ToList()[0].Value);
            var res = await _categoryService.SaveCategoryAsync(category, userId);
            if (res) return ResultHelper.Success("添加成功");
            return ResultHelper.Error("添加失败");
        }
    }
}
